﻿using Apps.Common;
using Apps.Core;
using Apps.Models.Common;
using Apps.WebApi.Models;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Routing;
using System.Web.Script.Serialization;

namespace Apps.WebApi.Core
{

    public class JsonCallbackAttribute : ActionFilterAttribute
    {
        private const string CallbackQueryParameter = "callback";


        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            

            //url获取token
            var content = actionContext.Request.Properties[ConfigPara.MS_HttpContext] as HttpContextBase;
            var token = content.Request.Form[ConfigPara.Token];

            if (string.IsNullOrEmpty(token))
            {
                token = content.Request.QueryString[ConfigPara.Token];

                if (string.IsNullOrEmpty(token))
                {
                    {
                        //获取请求数据  
                        Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result;
                        string requestDataStr = "";
                        if (stream != null && stream.Length > 0)
                        {
                            stream.Position = 0; //当你读取完之后必须把stream的读取位置设为开始
                            using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
                            {
                                requestDataStr = reader.ReadToEnd().ToString();
                            }
                        }
                        if (requestDataStr != "")
                        {
                            dynamic obj = JsonHandler.Deserialize<dynamic>(requestDataStr);
                            token = obj.token;
                        }
                    }

                }
            }



            if (!string.IsNullOrEmpty(token))
            {
                //解密用户ticket,并校验用户名密码是否匹配

                //读取请求上下文中的Controller,Action,Id
                var routes = new RouteCollection();
                RouteConfig.RegisterRoutes(routes);
                RouteData routeData = routes.GetRouteData(content);
                //取出区域的控制器Action,id
                string controller = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                string action = actionContext.ActionDescriptor.ActionName;
                //URL路径
                string filePath = HttpContext.Current.Request.FilePath;
                //判断token是否有效
                int tokenStatus = LoginUserManage.ValidateTicket(token);
                if (tokenStatus != 1)
                {
                    HandleUnauthorizedRequest(actionContext, tokenStatus);
                }

                //判断是否角色组授权（如果不需要使用角色组授权可以注释掉这个方法，这样就是登录用户都可以访问所有接口）
                //if(!ValiddatePermission(token, controller, action, filePath))
                //{
                //    HandleUnauthorizedRequest(actionContext);
                //}

                //已经登录，有权限
                base.OnActionExecuting(actionContext);
            }
            //如果取不到身份验证信息，并且不允许匿名访问，则返回未验证401
            else
            {
                HandleUnauthorizedRequest(actionContext);
            }

        }
        protected void HandleUnauthorizedRequest(HttpActionContext filterContext, int tokenStatu)
        {

            var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;

            HttpRetuenCommonInfo obj = new HttpRetuenCommonInfo();
            obj.status = 1;      //0失败  1成功
            obj.message = "令牌已经失效或过期，请重新登陆";

            var json = new
            {
                info = obj,
                tokenStatus = tokenStatu,//1正常 2过期 3无效
            };


            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string str = serializer.Serialize(json);
            response.Content = new StringContent(str, Encoding.UTF8, "application/json");
        }
        protected  void HandleUnauthorizedRequest(HttpActionContext filterContext)
        {

            var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;

            HttpRetuenCommonInfo obj = new HttpRetuenCommonInfo();
            obj.status = 0;      //0失败  1成功
            obj.message = "未获取到令牌";

            var json = new
            {
                info = obj,
                tokenStatus = 3,//1正常 2过期 3无效
            };

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string str = serializer.Serialize(json);
            response.Content = new StringContent(str, Encoding.UTF8, "application/json");
        }

        public override void OnActionExecuted(HttpActionExecutedContext context)
        {
            //var callback = string.Empty;

            //if (IsJsonp(out callback))
            //{
            //    var jsonBuilder = new StringBuilder(callback);

            //    jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result);
            //    context.Response.Content = new StringContent(jsonBuilder.ToString());
            //}

            //base.OnActionExecuted(context);
        }

        private bool IsJsonp(out string callback)
        {
            callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter];

            return !string.IsNullOrEmpty(callback);
        }
    }

    public class NoFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)

        {
            //
        }
        public override void OnActionExecuted(HttpActionExecutedContext context)
        {
            //
        }
    }


}